<template>
  <div class="profile-container">
    <ProfileHeader />
    <div class="wrapper">
      <a-tabs v-model:activeKey="activeTab" style="width: 100%">
        <a-tab-pane key="basic_info" tab="基本资料">
          <div class="basic-info">
            <a-row :gutter="24">
              <a-col :span="8">
                <div class="avatar-section" @click="triggerFileInput">
                  <a-avatar :src="userInfo.face || avatarUrl" :size="180" />
                  <div class="avatar-upload">
                    <input
                      type="file"
                      @change="handleAvatarChange"
                      accept="image/*"
                      style="display: none"
                      ref="fileInput"
                    />
                    <span>点击图片修改头像</span>
                  </div>
                </div>
              </a-col>
              <a-col :span="16">
                <a-form :model="userInfo" layout="vertical">
                  <a-form-item label="昵称">
                    <a-input v-model:value="userInfo.nick" style="width: 400px" />
                  </a-form-item>
                  <a-form-item label="生日">
                    <a-space>
                      <a-select v-model:value="userInfo.birthYear" style="width: 100px">
                        <a-select-option v-for="year in years" :key="year" :value="year">
                          {{ year }}年
                        </a-select-option>
                      </a-select>
                      <a-select v-model:value="userInfo.birthMonth" style="width: 80px">
                        <a-select-option v-for="month in months" :key="month" :value="month">
                          {{ month }}月
                        </a-select-option>
                      </a-select>
                      <a-select v-model:value="userInfo.birthDay" style="width: 80px">
                        <a-select-option v-for="day in days" :key="day" :value="day">
                          {{ day }}日
                        </a-select-option>
                      </a-select>
                    </a-space>
                  </a-form-item>
                  <a-form-item label="性别/星座">
                    <a-space>
                      <a-select v-model:value="userInfo.gender" style="width: 100px">
                        <a-select-option value="男">男</a-select-option>
                        <a-select-option value="女">女</a-select-option>
                      </a-select>
                      <!-- <span>{{ calculateZodiac }}</span> -->
                    </a-space>
                  </a-form-item>
                  <a-form-item label="所在地区">
                    <a-select v-model:value="userInfo.location" style="width: 100px">
                      <a-select-option
                        v-for="province in provinces"
                        :key="province"
                        :value="province"
                      >
                        {{ province }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item label="个人简介">
                    <a-input v-model:value="userInfo.introduction" style="width: 400px" />
                  </a-form-item>
                  <a-form-item>
                    <a-button type="primary" @click="saveUserInfo">确认保存</a-button>
                  </a-form-item>
                </a-form>
              </a-col>
            </a-row>
          </div>
        </a-tab-pane>
        <a-tab-pane key="change_phone" tab="修改手机">
          <div class="change-phone">
            <a-form layout="vertical">
              <a-form-item label="当前手机号">
                <a-input :value="userInfo.mobile" disabled />
              </a-form-item>
              <a-form-item label="新手机号">
                <a-input-group compact>
                  <a-select default-value="+86" style="width: 20%">
                    <a-select-option value="+86">+86</a-select-option>
                    <!-- 其他国家区号 -->
                  </a-select>
                  <a-input
                    style="width: 80%"
                    v-model:value="newPhone"
                    placeholder="请输入新手机号码"
                  />
                </a-input-group>
              </a-form-item>
              <a-form-item label="验证码">
                <a-space>
                  <a-input v-model:value="verificationCode" placeholder="请输入验证码" />
                  <a-button @click="sendVerificationCode">获取验证码</a-button>
                </a-space>
              </a-form-item>
              <a-form-item>
                <a-button type="primary" @click="changePhone">确认修改</a-button>
              </a-form-item>
            </a-form>
          </div>
        </a-tab-pane>
        <a-tab-pane key="change_password" tab="修改密码">
          <div class="change-password">
            <a-form layout="vertical">
              <a-form-item label="手机号">
                <a-input :value="userInfo.mobile" disabled />
              </a-form-item>
              <a-form-item label="验证码">
                <a-space>
                  <a-input v-model:value="passwordVerificationCode" placeholder="请输入验证码" />
                  <a-button @click="sendPasswordVerificationCode">获取验证码</a-button>
                </a-space>
              </a-form-item>
              <a-form-item label="新密码">
                <a-input-password
                  v-model:value="newPassword"
                  placeholder="请输入6-12位字母字组合"
                />
              </a-form-item>
              <a-form-item>
                <a-button type="primary" @click="changePassword">确认修改</a-button>
              </a-form-item>
            </a-form>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import ProfileHeader from './profileHeader.vue'
import { userStore } from '@/stores/user'
import { getSmsCode, updatePwdAPI, updateAvatarAPI, updateNicknameAPI, updateInfoAPI } from '@/api/user'
import { message } from 'ant-design-vue'
import axios from 'axios'

const store = userStore()

const activeTab = ref('basic_info')
const avatarUrl = new URL('@/assets/imgs/default-head-1.webp', import.meta.url).href

const userInfo = reactive({
  ...store?.userInfo,
  // avatar: '用户头像URL',
  // nickname: '奥特曼大战假面骑士',
  birthYear: '1995',
  birthMonth: '01',
  birthDay: '01',
  gender: '男',
  zodiac: '摩羯座',
  location: '上海市'
  // introduction: '奥特曼大战假面骑士'
})

const currentPhone = ref('182****3742')
const newPhone = ref('')
const verificationCode = ref('')
const passwordVerificationCode = ref('')
const newPassword = ref('')

const saveUserInfo = async () => {
  try {
    if (userInfo.nick) {
      await updateNicknameAPI({ nickname: userInfo.nick })
    }
    if (userInfo.introduction) {
      await updateInfoAPI({ introduction: userInfo.introduction })
    }
    message.success('个人信息更新成功')
    await store.getUserInfo() // 刷新个人中心数据
  } catch (error) {
    console.error('更新个人信息时出错:', error)
    message.error('更新个人信息失败,请检查输入并重试')
  }
}

const calculateZodiac = computed(() => {
  // 实现根据生日计算星座的逻辑
  return '摩羯座'
})

const sendVerificationCode = async () => {
  try {
    const params = {
      mobile: newPhone.value,
      type: 'changePhone'
    }
    await getSmsCode(params)
    message.success('验证码发送成功')
  } catch (error) {
    console.error('发送验证码失败', error)
    message.error('发送验证码失败,请稍后重试')
  }
}

const changePhone = async () => {
  try {
    const params = {
      mobile: userInfo.mobile.toString(),
      country_code: 86
    }
    await updatePwdAPI(params)
    message.success('手机号修改成功')
    // 更新成功后的处理,比如刷新用户信息
  } catch (error) {
    console.error('修改手机号失败', error)
    message.error('修改手机号失败,请检查输入并重试')
  }
}

const sendPasswordVerificationCode = async () => {
  try {
    const params = {
      mobile: userInfo.mobile.toString(),
      country_code: 86
    }
    await getSmsCode(params)
    message.success('密码修改证码发送成功')
  } catch (error) {
    console.error('发送密码修改验证码失败', error)
    message.error('发送验证码失败,请稍后重试')
  }
}

const changePassword = async () => {
  try {
    const params = {
      v_code: passwordVerificationCode.value,
      pwd: newPassword.value
    }
    await updatePwdAPI(params)
    message.success('密码修改成功')
    // 更新成功后的处理,比如清除输入框或重定向
  } catch (error) {
    console.error('修改密码失败', error)
    message.error('修改密码失败,请检查输入并重试')
  }
}

const currentYear = new Date().getFullYear()
const years = Array.from({ length: 100 }, (_, i) => currentYear - i)
const months = Array.from({ length: 12 }, (_, i) => i + 1)
const days = Array.from({ length: 31 }, (_, i) => i + 1)

const provinces = [
  '北京市',
  '天津市',
  '河北省',
  '山西省',
  '内蒙古自治区',
  '辽宁省',
  '吉林省',
  '黑龙江省',
  '上海市',
  '江苏省',
  '浙江省',
  '安徽省',
  '福建省',
  '江西省',
  '山东省',
  '河南省',
  '湖北省',
  '湖南省',
  '广东省',
  '广西壮族自治区',
  '海南省',
  '重庆市',
  '四川省',
  '贵州省',
  '云南省',
  '西藏自治区',
  '陕西省',
  '甘肃省',
  '青海省',
  '宁夏回族自治区',
  '新疆维吾尔自治区',
  '台湾省',
  '香港特别行政区',
  '澳门特别行政区'
]

const fileInput = ref(null)

const triggerFileInput = () => {
  fileInput.value.click()
}

const handleAvatarChange = async (event) => {
  const file = event.target.files[0]
  if (file) {
    if (file.size > 6 * 1024 * 1024) {
      message.error('文件大小不能超过6M')
      return
    }

    const formData = new FormData()
    formData.append('file', file)
    formData.append('token', '22ab27409e8a49d7acf160057a2f0cde')
    try {
      const response = await axios.post('https://api.superbed.cn/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      // 更新用户头像
      userInfo.face = response.data.url
      message.success('头像上传成功')

      // 调用API更新用户信息
      try {
        await updateAvatarAPI({ userHeaderImg: response.data.url })
        message.success('头像更新成功')
        await store.getUserInfo() // 刷新个人中心数据
      } catch (error) {
        message.error('头像更新失败')
        console.error(error)
      }
    } catch (error) {
      message.error('头像上传失败')
      console.error(error)
    }
  }
}
</script>

<style lang="scss" scoped>
.profile-container {
  width: 980px;

  .profile-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    // border-bottom: 1px solid #f0f0f0;
    background: url('@/assets/imgs/profile-bg.webp') no-repeat;
    background-size: 100% 100%;
    width: 100%;
    .user-info {
      margin-left: 20px;

      h2 {
        margin: 0;
        font-size: 18px;
      }

      p {
        margin: 5px 0 0;
        color: #666;
      }
    }
  }
  .wrapper {
    background: #fff;
    border-radius: 10px;
    padding: 10px 20px;
  }
  .basic-info {
    .avatar-section {
      // text-align: center;
      // margin-bottom: 20px;
      display: flex;
      align-items: center;
      flex-direction: column;
      justify-content: center;
      width: 200px;
      height: 200px;
      border-radius: 10px;
      overflow: hidden;
      background: RGBA(240, 240, 240, 1);
      cursor: pointer;
      position: relative;
      .avatar-upload {
        margin-top: 10px;
        color: #fff;
        cursor: pointer;
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background: #000;
        opacity: 0.5;
        span {
          cursor: pointer;
        }
      }
    }

    .ant-form-item {
      margin-bottom: 24px;
    }

    .ant-form-item-label {
      text-align: left;

      label {
        color: #333;
        font-size: 14px;
      }
    }

    .ant-input,
    .ant-select,
    .ant-textarea {
      border-radius: 4px;
    }
  }

  .change-phone,
  .change-password {
    max-width: 400px;
    margin: 0 auto;
  }

  :deep(.ant-tabs-nav) {
    margin-bottom: 20px;
  }

  :deep(.ant-form-item-label) {
    font-weight: bold;
  }

  .ant-input,
  .ant-select,
  .ant-input-group-wrapper {
    width: 100%;
  }

  .ant-space {
    width: 100%;

    .ant-input {
      flex: 1;
    }

    .ant-btn {
      margin-left: 10px;
    }
  }

  .ant-btn-primary {
    width: 100%;
  }
  .ant-btn-primary {
    width: 200px;
    height: 40px;
    border-radius: 20px;
    font-size: 16px;
    background-color: #16b13a;
    color: #fff;
    // border-color: #16b13a;
  }

  :deep(.ant-tabs) {
    .ant-tabs-nav {
      &::before {
        border-bottom-color: rgba(22, 177, 58, 0.1);
      }

      .ant-tabs-tab {
        color: rgba(0, 0, 0, 0.65);

        &:hover {
          color: rgba(22, 177, 58, 0.8);
        }

        &.ant-tabs-tab-active .ant-tabs-tab-btn {
          color: rgba(22, 177, 58, 1);
        }
      }

      .ant-tabs-ink-bar {
        background-color: rgba(22, 177, 58, 1);
      }
    }
  }
}
</style>
